import React, { ReactNode } from 'react'
import '@/app/component/form.css'
import classNames from 'classnames';
import { X } from 'lucide-react';

/** 辅助类型：根据多选状态推导值类型 */
type TagsValue<T, IsNumber> = IsNumber extends true ? {label: string, value: number} : {label: string, value: string};

interface MyTagsProps<T, IsNumber extends boolean = false> {
  value: TagsValue<T, IsNumber>[] //数组类型
  onChange?: (value: TagsValue<T, IsNumber>[]) => void //数组类型
  number?: IsNumber
  prefix?: ReactNode // 前缀
  suffix?: ReactNode // 后缀
  className?: string // 自定义类名
  deletable?: boolean // 是否可删除 //需要传入onChange函数
}

const MyTags = <T, IsNumber extends boolean = false>({
  value,
  onChange,
  prefix,
  suffix,
  className,
  deletable = false
}: MyTagsProps<T, IsNumber>) => {
  // remove tag handler
  const handleRemoveTag = (item: TagsValue<T, IsNumber>) => {
    if (onChange && value) {
      const newValue = value.filter(v => v?.value !== item?.value);
      onChange(newValue);
    }
  };
  return (
    <ul className='tags-layout'>
      {
        value.map((item=>(<li key={item?.value}>
          <div className={classNames('tags-option', className)}>
            {/* 前缀 */}
            {prefix}
            <div className='tags-option-text'>{item?.label}</div>
            {/* 后缀 */}
            {suffix}
            {/* close按钮 */}
            {deletable && <X className='tags-option-close' onClick={()=>{
              handleRemoveTag(item);
            }} />}
          </div>
        </li>)))
      }
    </ul>
  )
}

export default MyTags